#ifndef FILE_SCANNER
#define FILE_SCANNER

#include <string>
#include <string.h>
#include <vector>
#include <map>
#include <dirent.h>
#include "Defines.cpp"

class FileScanner
{
private:
    std::string _rootPath;
    std::vector<dirent> _fileAttrs;
    std::map<std::string, dirent> _fileAttrMap;

    dirent* GetDirentByIndex(int index)
    {
        if(index < 0 || index>=_fileAttrs.size())
        {
            PrintLine("index 越界 index [%d], size [%d]", index, _fileAttrs.size());
            return NULL;
        }
        return &_fileAttrs[index];
    }

public:
    FileScanner(std::string directoryPath)
    {
        _rootPath = directoryPath;
        Scan();
    }

    bool Scan()
    {
        DIR *dir;
        dirent *ptr;
        dir = opendir(_rootPath.c_str());
        if (dir == NULL)
        {
            PrintLine("打开目录文件失败");
            return false;
        }
        _fileAttrMap.clear();
        _fileAttrs.clear();
        while ((ptr = readdir(dir)) != NULL)
        {
            if (ptr->d_type != DT_DIR && ptr->d_type != DT_REG)
            {
                continue;
            }
            if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
            {
                continue;
            }
            _fileAttrMap.insert(std::pair<std::string, dirent>(ptr->d_name, *ptr));
            _fileAttrs.push_back(*ptr);
        }
        SortFileAttr();
        return true;
    }

    void SortFileAttr()
    {
        std::vector<dirent> dirs, files;
        for(int i = 0;i<_fileAttrs.size();i++)
        {
            if(_fileAttrs[i].d_type == DT_DIR)
            {
                dirs.push_back(_fileAttrs[i]);
            }
            if(_fileAttrs[i].d_type == DT_REG)
            {
                files.push_back(_fileAttrs[i]);
            }
        }
        _fileAttrs.clear();
        _fileAttrs.insert(_fileAttrs.end(), dirs.begin(), dirs.end());
        _fileAttrs.insert(_fileAttrs.end(), files.begin(), files.end());
    }

    std::string GetFileNameByIndex(int index)
    {
        dirent *dir = GetDirentByIndex(index);
        if(dir == NULL)
        {
            return "";
        }
        return dir->d_name;
    }

    unsigned char GetFileTypeByIndex(int index)
    {
        dirent *dir = GetDirentByIndex(index);
        if(dir == NULL)
        {
            return 0;
        }
        return dir->d_type;
    }

    unsigned char GetFileTypeByName(std::string name)
    {
        if(_fileAttrMap.find(name.c_str()) == _fileAttrMap.end())
        {
            PrintLine("文件不存在 [%s]", name.c_str());
            return 0;
        }
        return _fileAttrMap[name.c_str()].d_type;
    }
    int GetLength()
    {
        return _fileAttrs.size();
    }
};

#endif